package com.geeyuu.android.activity;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.mapapi.core.GeoPoint;
import com.amap.mapapi.core.OverlayItem;
import com.amap.mapapi.map.ItemizedOverlay;
import com.amap.mapapi.map.MapActivity;
import com.amap.mapapi.map.MapController;
import com.amap.mapapi.map.MapView;
import com.amap.mapapi.map.MyLocationOverlay;
import com.amap.mapapi.map.Projection;
import com.geeyuu.android.GeeApplication;
import com.geeyuu.android.GeeApplication.GetLocationListener;
import com.geeyuu.android.GeeConstants;
import com.geeyuu.android.GeePrefrence;
import com.geeyuu.android.R;
import com.geeyuu.android.activity.BaseActivity.BaseHandler;
import com.geeyuu.android.model.BaseUserInfo;
import com.geeyuu.android.service.IMService;
import com.geeyuu.android.service.ProtocolCommand;
import com.geeyuu.android.service.ReceiveMsgHandle;
import com.geeyuu.android.service.ServiceManager;
import com.geeyuu.android.utils.AndroidUtil;
import com.geeyuu.android.utils.ImageLoder;
import com.geeyuu.android.utils.LogUtil;
import com.umeng.analytics.MobclickAgent;

public class Activity1 extends MapActivity {

    private static final String TAG = "Activity1";

    private MapView mMapView;
    private MapController mMapController;
    private GeoPoint point;
    private MyLocationOverlay mLocationOverlay;
    private MyLocationOverlayProxy mLocationOverlayProxy;

    private Button topRightButton;

    // private double lon;
    // private double lat;

    private ImageLoder imageLoder;

    // Drawable myMarker = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isWatingMsgFromService = true;
        super.onCreate(savedInstanceState);
        LogUtil.v(TAG, "onCreate");
        setContentView(R.layout.activity1_layout);

        imageLoder = new ImageLoder(getApplicationContext());

        mHandler = new MyHandler(this);

        mMapView = (MapView) findViewById(R.id.map_view);
        mMapView.setBuiltInZoomControls(true);
        mLocationOverlay = new MyLocationOverlay(this, mMapView);
        // mMapView.getOverlays().add(mLocationOverlay);
        mMapController = mMapView.getController();
        mMapController.setZoom(12);

        // File avatarFile = new File(GeeConstants.PATH_SMALL_IMAGE_FOLDER,
        // GeePrefrence.getMyMainPhotoId(getApplicationContext()));
        // if(avatarFile.exists() && avatarFile.length() > 0){
        // myMarker = Drawable.createFromPath(avatarFile.getAbsolutePath());
        // }else{
        // myMarker = getResources().getDrawable(R.drawable.da_marker_red);
        // }
        // myMarker.setBounds(0, 0, myMarker.getIntrinsicWidth(),
        // myMarker.getIntrinsicHeight());

        initTitleViews();
        initContentViews();

        startBindService();
    }

    /**
     * 某个类型的覆盖物，包含多个类型相同、显示方式相同、处理方式相同的项时，使用此类.
     */
    static class OverItemT extends ItemizedOverlay<OverlayItem> {
        private List<OverlayItem> GeoList = new ArrayList<OverlayItem>();
        private Drawable marker;
        private Context mContext;
        GeoPoint p;
        String mainPId;

        // ArrayList<BaseUserInfo> userInfos;

        public OverItemT(Drawable d, Context context, GeoPoint p, String mainPID) {
            super(boundCenterBottom(d));
            this.mContext = context;
            this.p = p;
            this.mainPId = mainPID;
            this.marker = d;
            // ArrayList<BaseUserInfo> userInfos =
            // BaseUserInfo.getAroundUser(mContext, 4,
            // BaseUserInfo.ORDER_BY_DISTANCE, BaseUserInfo.FILTER_ROLE_NOT_SET,
            // BaseUserInfo.USER_ONLINE);
            // if(null != userInfos){
            // for (BaseUserInfo userInfo : userInfos) {
            // String[] strs = userInfo.lonAndlat.split(",");
            // GeoPoint p = new GeoPoint((int) (Double.valueOf(strs[1]) * 1E6),
            // (int) (Double.valueOf(strs[0]) * 1E6));
            // GeoList.add(new OverlayItem(p, "P2", userInfo.distance + " km"));
            // }
            // }

            // 用给定的经纬度构造GeoPoint，单位是微度 (度 * 1E6)
            // GeoPoint p1 = new GeoPoint((int) (mLat1 * 1E6), (int) (mLon1 *
            // 1E6));
            // GeoPoint p2 = new GeoPoint((int) (mLat2 * 1E6), (int) (mLon2 *
            // 1E6));
            // GeoPoint p3 = new GeoPoint((int) (mLat3 * 1E6), (int) (mLon3 *
            // 1E6));
            // 构造OverlayItem的三个参数依次为：item的位置，标题文本，文字片段
            GeoList.add(new OverlayItem(p, "P1", "point1"));
            // GeoList.add(new OverlayItem(p2, "P2", "point2"));
            // GeoList.add(new OverlayItem(p3, "P3", "point3"));
            populate(); // createItem(int)方法构造item。一旦有了数据，在调用其它方法前，首先调用这个方法
        }

        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow) {
            // Projection接口用于屏幕像素点坐标系统和地球表面经纬度点坐标系统之间的变换
            Projection projection = mapView.getProjection();
            for (int index = size() - 1; index >= 0; index--) { // 遍历GeoList
                OverlayItem overLayItem = getItem(index); // 得到给定索引的item
                String title = overLayItem.getTitle();
                // 把经纬度变换到相对于MapView左上角的屏幕像素坐标
                Point point = projection.toPixels(overLayItem.getPoint(), null);
                // 可在此处添加您的绘制代码
                Paint paintText = new Paint();
                paintText.setColor(Color.BLACK);
                paintText.setTextSize(15);
                canvas.drawText(title, point.x - 30, point.y - 25, paintText); // 绘制文本
                // canvas.drawBitmap(BitmapFactory.decodeFile(GeeConstants.PATH_SMALL_IMAGE_FOLDER
                // + File.separator + userInfos.get(index).mainPhotoID),
                // point.x, point.y, paintText);
            }
            // drawPolygon(canvas,mapView.getProjection());
            super.draw(canvas, mapView, shadow);
            // 调整一个drawable边界，使得（0，0）是这个drawable底部最后一行中心的一个像素
            // if(marker == null){
            // File f = new File(GeeConstants.PATH_SMALL_IMAGE_FOLDER, mainPId);
            // if(f.exists() && f.length()>0){
            // marker = Drawable.createFromPath(f.getAbsolutePath());
            // marker.setBounds(0, 0, marker.getIntrinsicWidth(),
            // marker.getIntrinsicHeight());
            // }
            // }
            boundCenterBottom(marker);

        }

        @Override
        protected OverlayItem createItem(int i) {
            return GeoList.get(i);
        }

        @Override
        public int size() {
            return GeoList.size();
        }

        @Override
        // 处理当点击事件
        protected boolean onTap(int i) {
            setFocus(GeoList.get(i));
            Toast.makeText(this.mContext, GeoList.get(i).getSnippet(), Toast.LENGTH_SHORT).show();
            return true;
        }

        @Override
        public boolean onTap(GeoPoint point, MapView mapView) {
            return super.onTap(point, mapView);
        }
        // private void drawPolygon(Canvas canvas, Projection projection) {
        // Paint p = new Paint();
        // p.setColor(Color.RED);// 设置背景为红色
        // Path path = new Path();
        // for (int index = 0; index < size(); index++) {// 遍历GeoList
        // OverlayItem overLayItem = getItem(index); // 得到给定索引的item
        // // 把经纬度变换到相对于MapView左上角的屏幕像素坐标
        // Point point = projection.toPixels(overLayItem.getPoint(), null);
        // if (index == 0) {
        // path.moveTo(point.x, point.y);// 此点为多边形的起点
        // } else {
        // path.lineTo(point.x, point.y);
        // }
        // }
        // path.close(); // 使这些点构成封闭的多边形
        // canvas.drawPath(path, p);
        // }
    }

    @Override
    protected void onResume() {
        LogUtil.v(TAG, "onResume");

        this.mLocationOverlay.enableMyLocation();
        this.mLocationOverlay.enableCompass();

        super.onResume();

        MobclickAgent.onResume(this);

        changeMode();

        final GeeApplication geeApplication = (GeeApplication) getApplication();
        geeApplication.setLocationListener(new GetLocationListener() {
            @Override
            public void onFinish(double[] lonAndLat) {
                point = new GeoPoint((int) (lonAndLat[1] * 1E6), (int) (lonAndLat[0] * 1E6));
                mHandler.sendEmptyMessage(INIT_LOC);
                mHandler.sendEmptyMessage(INIT_AVATAR);
            }

            @Override
            public void onFail(double[] lastLonAndLat) {
                point = new GeoPoint((int) (lastLonAndLat[1] * 1E6), (int) (lastLonAndLat[0] * 1E6));
                mHandler.sendEmptyMessage(INIT_LOC);
                mHandler.sendEmptyMessage(INIT_AVATAR);
            }
        });

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onPause() {
        LogUtil.v(TAG, "onPause");

        this.mLocationOverlay.disableMyLocation();
        this.mLocationOverlay.disableCompass();
        super.onPause();

        MobclickAgent.onPause(this);

        if (null != sensorEventListener && null != sensorManager && howMeetFriend == SHAKE_FRIEND) {
            sensorManager.unregisterListener(sensorEventListener);
        }

        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        }

    }

    public static final int FIRST_LOCATION = 1002;
    public static final int INIT_LOC = 1003;
    public static final int INIT_AVATAR = 1004;
    private Handler mHandler;

    static class MyHandler extends Handler {
        public final WeakReference<Activity1> activity1;

        public MyHandler(Activity activity) {
            activity1 = new WeakReference<Activity1>((Activity1) activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            case FIRST_LOCATION:
                activity1.get().mMapController.animateTo(activity1.get().mLocationOverlay.getMyLocation());
                break;

            case INIT_LOC:
                activity1.get().mMapController.setCenter(activity1.get().point);
                break;

            case INIT_AVATAR:
                ArrayList<BaseUserInfo> userInfos = BaseUserInfo.getAroundUser(activity1.get(), 4,
                        BaseUserInfo.ORDER_BY_DISTANCE, BaseUserInfo.FILTER_ROLE_NOT_SET, BaseUserInfo.USER_ONLINE);
                if (null != userInfos) {

                    for (BaseUserInfo userInfo : userInfos) {
                        String[] strs = userInfo.lonAndlat.split(",");
                        Drawable marker = null;
                        if (userInfo.mainPhotoID.equals(GeePrefrence.getMyMainPhotoId(activity1.get()))) {
                            File f = new File(GeeConstants.PATH_SMALL_IMAGE_FOLDER, userInfo.mainPhotoID);
                            if (f.exists() && f.length() > 0) {
                                marker = Drawable.createFromPath(f.getAbsolutePath());
                                marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());
                            }
                        }
                        OverItemT overItemT = new OverItemT(marker, activity1.get(), new GeoPoint(
                                (int) (Double.valueOf(strs[1]) * 1E6), (int) (Double.valueOf(strs[0]) * 1E6)),
                                userInfo.mainPhotoID);
                        activity1.get().mMapView.getOverlays().add(overItemT);
                    }
                }

                break;
            }
        }
    }

    private OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.top_left_button:
                String loc = GeePrefrence.getMyLocation(getApplicationContext());
                String[] lonAndLat = loc.split(",");
                point = new GeoPoint((int) (Double.valueOf(lonAndLat[1]) * 1E6),
                        (int) (Double.valueOf(lonAndLat[0]) * 1E6));
                mMapController.animateTo(point);
                break;

            case R.id.top_right_button:
                if (popupWindowMode.isShowing()) {
                    popupWindowMode.dismiss();
                }
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    popupWindow.showAsDropDown(topRightButton, 0, 0);
                }
                break;
            case R.id.meet_friend_text_view:
                howMeetFriend = MEET_FRIEND;
                meetFriendTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.meet_friend_icon, 0,
                        R.drawable.selected_icon, 0);
                shakeFriendTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.shake_icon, 0, 0, 0);
                changeMode();
                popupWindowMode.dismiss();
                break;
            case R.id.shake_friend_text_view:
                howMeetFriend = SHAKE_FRIEND;
                meetFriendTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.meet_friend_icon, 0, 0, 0);
                shakeFriendTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.shake_icon, 0,
                        R.drawable.selected_icon, 0);
                changeMode();
                popupWindowMode.dismiss();
                break;
            case R.id.role_all_text_view:
                role = ROLE_ALL;
                roleAllTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_all_icon, 0,
                        R.drawable.selected_icon, 0);
                role_1_TextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_1_icon, 0, 0, 0);
                role_0_TextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_0_icon, 0, 0, 0);
                popupWindow.dismiss();
                filterMeetData();
                break;
            case R.id.role_1_text_view:
                role = ROLE_1;
                roleAllTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_all_icon, 0, 0, 0);
                role_1_TextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_1_icon, 0,
                        R.drawable.selected_icon, 0);
                role_0_TextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_0_icon, 0, 0, 0);
                popupWindow.dismiss();
                filterMeetData();
                break;
            case R.id.role_0_text_view:
                role = ROLE_0;
                roleAllTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_all_icon, 0, 0, 0);
                role_1_TextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_1_icon, 0, 0, 0);
                role_0_TextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_0_icon, 0,
                        R.drawable.selected_icon, 0);
                popupWindow.dismiss();
                filterMeetData();
                break;
            case R.id.comfire_button:
                popupWindow.dismiss();
                break;

            case R.id.meet_friend_mode_button:
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                if (popupWindowMode.isShowing()) {
                    popupWindowMode.dismiss();
                } else {
                    if (howMeetFriend == SHAKE_FRIEND) {
                        popupWindowMode.showAsDropDown(v, imageLoder.screenWidth - popupWindowMode.getWidth(), 0);
                    } else {
                        popupWindowMode.showAsDropDown(v, 0, 0);
                    }
                }
                break;
            }
        }
    };

    private SensorManager sensorManager;
    private Sensor sensor;
    private SensorEventListener sensorEventListener;

    private void changeMode() {
        if (howMeetFriend == MEET_FRIEND) {
            isWatingMsgFromService = true;
            modeButton.setText("偶遇");
            if (null != topRightButton) {
                topRightButton.setVisibility(View.VISIBLE);
            }
            modeButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.vertical_line, 0, 0, 0);
            if (null != topLeftButton) {
                topLeftButton.setVisibility(View.VISIBLE);
            }
            if (shakeAllContainer.getVisibility() != View.INVISIBLE) {
                shakeAllContainer.setVisibility(View.INVISIBLE);
            }
            if (mMapView.getVisibility() != View.VISIBLE) {
                mMapView.setVisibility(View.VISIBLE);
            }
            if (null != sensorEventListener && null != sensorManager) {
                sensorManager.unregisterListener(sensorEventListener);
            }
        } else if (howMeetFriend == SHAKE_FRIEND) {
            isWatingMsgFromService = false;
            modeButton.setText("摇一摇");
            if (popupWindow.isShowing()) {
                popupWindow.dismiss();
            }
            modeButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            if (null != topRightButton) {
                topRightButton.setVisibility(View.GONE);
            }
            if (null != topLeftButton) {
                topLeftButton.setVisibility(View.GONE);
            }
            if (shakeAllContainer.getVisibility() != View.VISIBLE) {
                shakeAllContainer.setVisibility(View.VISIBLE);
            }
            if (mMapView.getVisibility() != View.INVISIBLE) {
                mMapView.setVisibility(View.INVISIBLE);
            }
            if (null == sensorManager) {
                sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
            }
            if (null == sensor) {
                sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            }
            if (null != sensor && null != sensorManager) {
                if (null == sensorEventListener) {
                    sensorEventListener = new SensorEventListener() {
                        @Override
                        public void onSensorChanged(SensorEvent event) {
                            float[] values = event.values;
                            if (values[0] > 11 || values[1] > 11 || values[2] > 11) {
                                shakeAction();
                            }
                        }

                        @Override
                        public void onAccuracyChanged(Sensor sensor, int accuracy) {
                        }
                    };
                }
                sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
            } else {
                Toast.makeText(this, "抱歉，您的手机不支持此功能", Toast.LENGTH_SHORT).show();
            }
        }
    }

    Button modeButton;
    View modeContainer;
    Button topLeftButton;

    private void initTitleViews() {

        topLeftButton = (Button) findViewById(R.id.top_left_button);
        topLeftButton.setVisibility(View.VISIBLE);
        topLeftButton.setText("我的位置");
        topLeftButton.setTextSize(14);
        topLeftButton.setPadding(AndroidUtil.dip2px(this, 5), 0, 0, 0);
        ViewGroup.LayoutParams vl = topLeftButton.getLayoutParams();
        if (null == vl) {
            vl = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT);
        } else {
            vl.width = ViewGroup.LayoutParams.WRAP_CONTENT;
            vl.height = ViewGroup.LayoutParams.FILL_PARENT;
        }
        topLeftButton.setLayoutParams(vl);
        topLeftButton.setOnClickListener(mOnClickListener);

        topRightButton = (Button) findViewById(R.id.top_right_button);
        topRightButton.setVisibility(View.VISIBLE);
        topRightButton.setPadding(0, 0, AndroidUtil.dip2px(this, 27), 0);
        topRightButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.vertical_line, 0,
                R.drawable.more_filter_button, 0);
        topRightButton.setOnClickListener(mOnClickListener);

        modeButton = (Button) findViewById(R.id.meet_friend_mode_button);
        modeButton.setVisibility(View.VISIBLE);
        modeButton.setOnClickListener(mOnClickListener);

        modeContainer = findViewById(R.id.mode_view_container);
        modeContainer.setVisibility(View.VISIBLE);

    }

    private View shakeAllContainer;
    private RelativeLayout shakeUpContainer;
    private RelativeLayout shakeDownContainer;
    private ImageView upLine;
    private ImageView downLine;
    private View shakeFlower;
    private TranslateAnimation upTa;
    private TranslateAnimation downTa;
    private int shakeViewHeight = 0;

    private TextView meetFriendTextView;
    private TextView shakeFriendTextView;
    private TextView roleAllTextView;
    private TextView role_1_TextView;
    private TextView role_0_TextView;
    private PopupWindow popupWindow;
    private PopupWindow popupWindowMode;

    private static final int MEET_FRIEND = 0;
    private static final int SHAKE_FRIEND = 1;
    private int howMeetFriend = MEET_FRIEND;

    private static final int ROLE_ALL = 0;
    private static final int ROLE_1 = 1;
    private static final int ROLE_0 = 2;
    private int role = ROLE_ALL;

    private void initContentViews() {

        View filterContainer = getLayoutInflater().inflate(R.layout.meet_friend_popup_layout, null);
        roleAllTextView = (TextView) filterContainer.findViewById(R.id.role_all_text_view);
        role_1_TextView = (TextView) filterContainer.findViewById(R.id.role_1_text_view);
        role_0_TextView = (TextView) filterContainer.findViewById(R.id.role_0_text_view);
        roleAllTextView.setOnClickListener(mOnClickListener);
        role_1_TextView.setOnClickListener(mOnClickListener);
        role_0_TextView.setOnClickListener(mOnClickListener);
        popupWindow = new PopupWindow(filterContainer, WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT);

        View modeContainer = getLayoutInflater().inflate(R.layout.meet_friend_mode_layout, null);
        meetFriendTextView = (TextView) modeContainer.findViewById(R.id.meet_friend_text_view);
        shakeFriendTextView = (TextView) modeContainer.findViewById(R.id.shake_friend_text_view);
        meetFriendTextView.setOnClickListener(mOnClickListener);
        shakeFriendTextView.setOnClickListener(mOnClickListener);
        popupWindowMode = new PopupWindow(modeContainer, WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT);

        shakeAllContainer = findViewById(R.id.shake_all_container);
        shakeUpContainer = (RelativeLayout) findViewById(R.id.shake_up_container);
        shakeDownContainer = (RelativeLayout) findViewById(R.id.shake_down_container);
        upLine = (ImageView) findViewById(R.id.up_line);
        downLine = (ImageView) findViewById(R.id.down_line);
        shakeFlower = findViewById(R.id.shake_flower);

    }

    private boolean isShakeAnimationPlaying = false;

    private void shakeAction() {
        if (isShakeAnimationPlaying) {
            return;
        }
        if (upLine.getVisibility() != View.VISIBLE || downLine.getVisibility() != View.VISIBLE) {
            upLine.setVisibility(View.VISIBLE);
            downLine.setVisibility(View.VISIBLE);
        }
        if (shakeViewHeight == 0) {
            shakeViewHeight = shakeFlower.getHeight() / 2 + 10;
        }
        if (null == upTa) {
            upTa = new TranslateAnimation(0, 0, 0, -shakeViewHeight);
            upTa.setDuration(1000);
            upTa.setFillAfter(true);
        }
        shakeUpContainer.startAnimation(upTa);
        if (null == downTa) {
            downTa = new TranslateAnimation(0, 0, 0, shakeViewHeight);
            downTa.setFillAfter(true);
            downTa.setDuration(1000);
            downTa.setAnimationListener(new AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    isShakeAnimationPlaying = true;
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    submitShakeData();
                }
            });
        }
        shakeDownContainer.startAnimation(downTa);
    }

    private void submitShakeData() {
        showProgressDialog("摇一摇", "正在识别同时摇一摇的用户", false);
        String loc = GeePrefrence.getMyLocation(getApplicationContext());
        Bundle bundle = new Bundle();
        bundle.putStringArray("locArray", loc.split(","));
        sendMsgToService(ProtocolCommand.CMD_SHAKE_SHAKE, bundle);
    }

    private void filterMeetData() {

    }

    protected void onReceiveMsgFromService(int cmd, Bundle bundle, boolean isMsgNormal) {
        switch (cmd) {
        case ProtocolCommand.CMD_SHAKE_SHAKE:
            cancelProgressDialog();
            if (isMsgNormal) {

            } else {

            }
            isShakeAnimationPlaying = false;
            break;
        }
    }

    protected void onConnectServiceCallBack() {

    }

    @Override
    protected void onDestroy() {
        isWatingMsgFromService = false;
        if (null != imageLoder) {
            imageLoder.destory();
        }
        stopBindService();
        LogUtil.v(TAG, "onDestroy");
        super.onDestroy();
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

    private boolean isWatingMsgFromService = false;
    private ServiceManager mServiceManager;
    private boolean isAutoCloseDialog = false;
    private ProgressDialog pd = null;
    private static final int TIME_OUT = 50 * 1000;
    private TimerTask timerTask = null;
    private Timer timer = null;
    private int cmd;

    protected void startBindService() {
        if (null == mServiceManager) {
            mServiceManager = new ServiceManager(getApplicationContext(), IMService.class,
                    new BaseHandler(this, TAG, 1));
        }
    }

    protected void stopBindService() {
        if (null != mServiceManager) {
            mServiceManager.doUnbindService(TAG);
        }
    }

    protected void onReceiverMsgFromHandler(int cmd, Bundle bundle, int errorCode) {
        if (isWatingMsgFromService) {
            isWatingMsgFromService = false;
            if (null != timerTask) {
                timerTask.cancel();
            }
            if (null != timer) {
                timer.cancel();
            }
            if (isAutoCloseDialog) {
                isAutoCloseDialog = false;
                cancelProgressDialog();
            }
            onReceiveMsgFromService(cmd, bundle, errorCode == ReceiveMsgHandle.ERROR_CODE_OK ? true : false);
        } else {
            LogUtil.e(TAG, "没有消息在等待, cmd: " + cmd);
        }
    }

    protected void cancelProgressDialog() {
        if (null != pd && pd.isShowing()) {
            pd.cancel();
        }
    }

    protected void showProgressDialog(String title, CharSequence content, boolean isAutoClose) {
        if (null == pd) {
            pd = new ProgressDialog(this);
            pd.setIndeterminate(true);
            pd.setCancelable(true);
            pd.setTitle(title);
            pd.setMessage(content);
            pd.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    isWatingMsgFromService = false;
                    isAutoCloseDialog = false;
                    if (null != timerTask) {
                        timerTask.cancel();
                    }
                    if (null != timer) {
                        timer.cancel();
                    }
                }
            });
        }
        if (!pd.isShowing()) {
            isAutoCloseDialog = isAutoClose;
            pd.show();
        }
    }

    protected void showProgressDialog(int titleRes, int content, boolean isAutoClose) {
        if (null == pd) {
            pd = new ProgressDialog(this);
            pd.setIndeterminate(true);
            pd.setCancelable(true);
            pd.setTitle(titleRes);
            pd.setMessage(getString(content));
            pd.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    isAutoCloseDialog = false;
                    isWatingMsgFromService = false;
                    if (null != timerTask) {
                        timerTask.cancel();
                    }
                    if (null != timer) {
                        timer.cancel();
                    }
                }
            });
        }
        if (!pd.isShowing()) {
            isAutoCloseDialog = isAutoClose;
            pd.show();
        }
    }

    protected void sendMsgToService(int command, Bundle bundle) {
        cmd = command;
        if (!AndroidUtil.isNetworkAvailable(this)) {
            LogUtil.w(TAG, "没有网络连接");
            Toast.makeText(getApplicationContext(), "没有网络连接", Toast.LENGTH_SHORT).show();
            onReceiveMsgFromService(cmd, null, false);
            return;
        }
        isWatingMsgFromService = true;
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if (isWatingMsgFromService) {
                    LogUtil.i(TAG, "activity请求超时");
                    isWatingMsgFromService = false;
                    Looper.prepareMainLooper();
                    if (isAutoCloseDialog) {
                        isAutoCloseDialog = false;
                        cancelProgressDialog();
                    }
                    onReceiveMsgFromService(cmd, null, false);
                }
            }
        };
        timer = new Timer();
        timer.schedule(timerTask, TIME_OUT);
        Message message = new Message();
        message.obj = TAG;
        message.what = command;
        if (null != bundle) {
            message.setData(bundle);
        }
        if (null != mServiceManager) {
            try {
                mServiceManager.sendMsgToService(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else {
            LogUtil.e(TAG, "mServiceManager没有初始化");
        }
    }

}
